package mysql

import (
	"fmt"
	"github.com/spf13/viper"
	"order/model"
	"order/proto"
	"strconv"
	"time"
)

func SubmitOrder(houseId, startDate, endDate, userName string) (uint, error) {
	// 更新数据
	var orderInfo model.OrderHouse

	hid, _ := strconv.Atoi(houseId)
	orderInfo.HouseId = uint(hid)
	orderInfo.Begin_date, _ = time.Parse("2006-01-02", startDate)
	orderInfo.End_date, _ = time.Parse("2006-01-02", endDate)

	dur := orderInfo.End_date.Sub(orderInfo.Begin_date)
	// 订房天数
	orderInfo.Days = int(dur.Hours()) / 24
	orderInfo.Status = "WAIT_ACCEPT"

	// 房屋单价，总价
	var house model.House
	err := GormDB.Where("id = ?", hid).Find(&house).Select("price").Error
	if err != nil {
		fmt.Println("查询房屋信息失败!", err)
		return 0, err
	}
	fmt.Println("----------houseinfo: ", house)

	orderInfo.House_price = house.Price
	orderInfo.Amount = house.Price * orderInfo.Days

	// select user_id from user where name = userName
	var userId uint
	//	GormDB.Raw("select id from user where name = ?", userName).Scan(&userData).Error{
	err = GormDB.Model(&model.User{}).Select("id").Where("name = ?", userName).Scan(&userId).Error
	if err != nil {
		fmt.Println("查询user_id失败", err)
		return 0, err
	}

	orderInfo.UserId = userId

	err = GormDB.Create(&orderInfo).Error
	if err != nil {
		fmt.Println("插入order_house数据库失败", err)
		return 0, err
	}

	return orderInfo.ID, nil
}

func GetOrders(userName, role string) ([]*order.OrdersData, error) {

	// 最终需要的数据
	var orderResp []*order.OrdersData
	// 获取当前用户的所有订单
	var orderinfos []model.OrderHouse

	var userId uint
	// User{}用于创建User结构体的新实例。这类似于在其他编程语言中创建类的对象。
	err := GormDB.Model(model.User{}).Select("id").Where("name = ?", userName).Scan(&userId).Error
	if err != nil {
		fmt.Println("查询user_id失败", err)
		return nil, err
	}

	//查询租户的所有的订单
	if role == "custom" {
		err = GormDB.Where("user_id = ?", userId).Find(&orderinfos).Error
		if err != nil {
			fmt.Println("查询订单信息失败, ", err)
			return nil, err
		}
	} else {
		// 查询房东的订单  以房东视角来查看订单(房东的房子被别人下单，自己不一定是下单人)
		// 查看房东的房子下的所有订单
		var houses []model.House
		err = GormDB.Where("user_id = ?", userId).Find(&houses).Error
		if err != nil {
			fmt.Println("查询用户房屋信息失败,err: ", err)
			return nil, err
		}

		for _, house := range houses {
			var tempOrders []model.OrderHouse
			err = GormDB.Where("house_id = ?", house.ID).Find(&tempOrders).Error
			if err != nil {
				fmt.Println("查询房屋订单信息失败，err: ", err)
				return nil, err
			}
			//  tempOrders... 用于解压缩tempOrders切片的元素，并将它们作为单独的参数传递给append()函数
			orderinfos = append(orderinfos, tempOrders...)
		}
	}

	// 遍历订单数据
	for _, orderinfo := range orderinfos {
		var orderData order.OrdersData
		orderData.Ctime = orderinfo.CreatedAt.Format("2006-01-02")
		orderData.OrderId = int32(orderinfo.ID)
		orderData.HouseId = int32(orderinfo.HouseId)
		orderData.StartDate = orderinfo.Begin_date.Format("2006-01-02")
		orderData.EndDate = orderinfo.End_date.Format("2006-01-02")
		orderData.Days = int32(orderinfo.Days)
		orderData.Amount = int32(orderinfo.Amount)
		orderData.Status = orderinfo.Status
		orderData.Comment = orderinfo.Comment

		// 关联house表
		var temphouse model.House
		err = GormDB.Where("id = ?", orderinfo.HouseId).Find(&temphouse).Error
		if err != nil {
			fmt.Println("获取房屋信息失败，err: ", err)
			return nil, err
		}
		orderData.Title = temphouse.Title
		orderData.ImgUrl = "http://" + viper.GetString("server.localAddress") + "/" + temphouse.Index_image_url

		orderResp = append(orderResp, &orderData)
		// &orderData是要追加的数据，orderResp是要追加到的切片。通过将追加的数据作为参数传递给append函数，并将返回的结果重新赋值给orderResp，就可以将数据追加到切片中
	}

	return orderResp, nil
}

// UpdateStatus 更新订单状态
func UpdateStatus(action, id, reason string) error {
	if action == "accept" {
		//标示房东同意订单
		return GormDB.Model(&model.OrderHouse{}).Where("id = ?", id).Update("status", "WAIT_COMMENT").Error
	} else {
		//表示房东不同意订单  如果拒单把拒绝的原因写到comment中
		return GormDB.Model(&model.OrderHouse{}).Where("id = ?", id).Updates(map[string]interface{}{"status": "REJECTED", "comment": reason}).Error
	}
}

// 发表评论
func PutComment(orderId, comment string) error {
	return GormDB.Model(&model.OrderHouse{}).Where("id = ?", orderId).Updates(map[string]interface{}{"status": "COMMENTED", "comment": comment}).Error
}
